<?php

namespace app\delivery\logic;

use app\admin\controller\system\Config;
use app\common\library\RedissLock;
use app\common\service\CommonSystemImportService;
use think\facade\Db;

class DeliveryLogic extends BasicLogic
{

    /**
     * @desc   获取发送消息配置列表接口
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function orderList($params=[]){
        $limit            = getIsset($params,'limit',20);
        $package_id       = $params['package_id']??'';
        $shop_id          = $params['shop_id']??'';
        $order_number     = $params['order_number']??'';
        $order_id         = $params['order_id']??'';
        $tracking_number  = $params['tracking_number']??'';
        $create_time      = getIsset($params,'create_time');
        $where            = [];


        if($order_id){
            $order_ids_raw = trim($params['order_id']);
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');
            if (!empty($order_ids_filtered)) {
                $where[] = ['order_id', 'in', $order_ids_filtered];
            }
        }


        if($package_id){
            $where[] = ['package_id', '=', $package_id];
        }


        if($order_number){
            $order_numbers_raw = trim($params['order_number']);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            if (!empty($order_numbers_filtered)) {
                $where[] = ['order_number', 'in', $order_numbers_filtered];
            }
        }


        if($tracking_number){
            $where[] = ['tracking_number','=',$tracking_number];
        }


        if($shop_id){
            $where[] = ['shop_id','=',$shop_id];
        }

        if (!empty($create_time)){
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        $field = '*';
        $res   = Db::name('order_process')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        //批量获取店铺名称;
        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');
        //批量获取订单的信息;
        $order_ids       = array_column($list,'order_id');
        $order_infos     = Db::name('order_info')->field('id,order_id,spu,sku,variant_title,quantity,price')->whereIn('order_id',$order_ids)->select()->toArray();
        //批量获取图片地址;
        $sku_info        = array_column($order_infos,'sku');
        $skus            = [];
        foreach($sku_info as $sku){
            if(strpos($sku, '+')!== false){
                continue;
            }
            $lastSlashPosition = strpos($sku, '/');
            if ($lastSlashPosition !== false) {
                $sku = substr($sku, 0, $lastSlashPosition); // 保留 / 之前的部分
            }
            $skus[] = $sku;
        }
        $sku_image_info  = Db::name('product_seller_sku')->field('id,seller_sku,image_info')->whereIn('seller_sku',$skus)->select()->toArray();
        $image_infos_map = array_column($sku_image_info,'image_info','seller_sku');

        //批量获取收件人信息;
        $customer_infos     = Db::name('order_customer')->field('order_id,first_name,last_name')->whereIn('order_id',$order_ids)->select()->toArray();
        $customer_infos_map = array_column($customer_infos,null,'order_id');
        foreach($order_infos as $k=>$v){
            $lastSlashPosition = strpos($v['sku'], '/');
            if ($lastSlashPosition !== false) {
                $v['sku'] = substr($sku, 0, $lastSlashPosition); // 保留 / 之前的部分
            }
            $imange_url = $image_infos_map[$v['sku']]??'';
            if(!$imange_url){
                $imange_url = self::get_imange_url($v['spu']);
            }
            if(!$imange_url){
                $imange_url = Config('Logisticskey.product_image_default');
            }
            $order_infos[$k]['imange_url'] = $imange_url;
            if(!$v['sku']){
                unset($order_infos[$k]);
            }
        }

        $order_infos     = array_values($order_infos);
        $order_infos_map = get_unique_order($order_infos);
        $countrys        = Config('Logisticskey.site_name');
        foreach($list as $k=>$v){
            $skus_map                  = $order_infos_map[$v['order_id']]??[];
            $customers_map             = $customer_infos_map[$v['order_id']]??[];
            $shopNames                 = $shop_names_map[$v['shop_id']]??[];
            $shop_name                 = $shopNames['name']??'';
            if(isset($customers_map['first_name']) && isset($customers_map['last_name'])){
                $customer                  = $customers_map['first_name'].' '.$customers_map['last_name'];
            }else{
                $customer                  = '';
            }

            $platform_name  = $v['shop_id'] == '20' ? 'Shopline2' :'Shopify';
            $list[$k]['shop_name']     = $platform_name.'：'.$shop_name;
            $list[$k]['sku_info']      = $skus_map;
            $list[$k]['customer_name'] = $customer;
            $list[$k]['country']       = $countrys[$v['country']] ? : $v['country'];
            $list[$k]['display_status']= '待审核';
            //获取订单状态;
            if($v['order_status'] == 1){
                $list[$k]['display_status'] = '已付款';
            }

        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }



    private function get_imange_url($spu=''){
          $info = Db::name('product_seller_sku')->where(['spu'=>$spu])->value('image_info');
          return $info;
    }



    /**
     * @desc   导入数据处理
     * @author luckyXiong
     * @date   2025-03-19
     */
    public function importInfo($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_DELIVERY_PAGE,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }




    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2025-03-19
     */
    public function import_order_delivery($params=[]){
        $key = 'import_order_delivery:'.time();
        $redis_lock = new RedissLock();
        $lock = $redis_lock::lock($key, $redis_lock::UNBLOCK, 300);

        $seller_sku         =   getIsset($params,'seller_sku');
        $spu_info           =   explode('-', $seller_sku);
        $spu                =   $spu_info[0]??'';
        $suggest_quantity   =   getIsset($params,'suggest_quantity');
        $suggest_days       =   getIsset($params,'suggest_days');
        $supply_name        =   getIsset($params,'supply_name');
        $purchase_price     =   getIsset($params,'purchase_price');
        $sku_1days          =   getIsset($params,'sku_1days');
        $sku_3days          =   getIsset($params,'sku_3days');
        $sku_7days          =   getIsset($params,'sku_7days');
        $sku_15days         =   getIsset($params,'sku_15days');
        $sku_30days         =   getIsset($params,'sku_30days');
        $sku_90days         =   getIsset($params,'sku_90days');
        $inventory_quantity =   getIsset($params,'inventory_quantity');
        $on_way_quantity    =   getIsset($params,'on_way_quantity');
        $safe_quantity      =   getIsset($params,'safe_quantity');
        $lastSlashPosition  =   strpos($seller_sku, '/');
        if ($lastSlashPosition !== false) {
            $seller_sku = substr($seller_sku, 0, $lastSlashPosition);
        }
        $exist_supply         =   Db::name('supply')->where('supply_name',$supply_name)->find();
        if(!$exist_supply){
            $supply_id = Db::name('supply')->insertGetId(
                [
                    'supply_name' =>$supply_name,
                    'created_time'=>date("Y-m-d H:i:s", time())
                ]);
        }else{
            $supply_id = $exist_supply['id'];
        }

        //获取产品图片;
        $image_url = Db::name('product_seller_sku')->where(['seller_sku'=>$seller_sku])->value('image_info');
        //数据入库逻辑
        $info = [
                    'spu'                => $spu,
                    'seller_sku'         => $seller_sku,
                    'suggest_quantity'   => $suggest_quantity,
                    'suggest_days'       => $suggest_days,
                    'inventory_quantity' => $inventory_quantity,
                    'on_way_quantity'    => $on_way_quantity,
                    'safe_quantity'      => $safe_quantity,
                    'purchase_price'     => $purchase_price,
                    'purchase_quantity'  => $suggest_quantity,
                    'sku_1days'          => $sku_1days,
                    'sku_3days'          => $sku_3days,
                    'sku_7days'          => $sku_7days,
                    'sku_15days'         => $sku_15days,
                    'sku_30days'         => $sku_30days,
                    'sku_90days'         => $sku_90days,
                    'image_url'          => $image_url??'',
                    'supply_id'          => $supply_id,
                    'supply_name'        => $supply_name,
                    'update_time'        =>date("Y-m-d H:i:s", time()),
                    'create_time'        =>date("Y-m-d H:i:s", time()),
        ];
        //update 2024-08-27
        $res = Db::name('purchase_stock_suggest')->insertGetId($info);
        $lock->unlock();
        $info['status'] = $res == 1 ? 1:2;
        return  $info;
    }


    /**
     * @param $row
     * @return string[]
     * @desc 数据title 导入组装数据结构
     */
    public function get_excel_row_data($row){
        return [
            'seller_sku'         => empty($row['A'])? '': trim($row['A']),
            'suggest_quantity'   => empty($row['B'])? '': trim($row['B']),
            'suggest_days'       => empty($row['C'])? '': trim($row['C']),
            'supply_name'        => empty($row['D'])? '': trim($row['D']),
            'purchase_price'     => empty($row['E'])? '': trim($row['E']),
            'sku_1days'          => empty($row['F'])? '': trim($row['F']),
            'sku_3days'          => empty($row['G'])? '': trim($row['G']),
            'sku_7days'          => empty($row['H'])? '': trim($row['H']),
            'sku_15days'         => empty($row['I'])? '': trim($row['I']),
            'sku_30days'         => empty($row['J'])? '': trim($row['J']),
            'sku_90days'         => empty($row['K'])? '': trim($row['K']),
            'inventory_quantity' => empty($row['L'])? '': trim($row['L']),
            'on_way_quantity'    => empty($row['M'])? '': trim($row['M']),
            'safe_quantity'      => empty($row['O'])? '': trim($row['O']),
        ];
    }






}